//
//  ICMAppointmentResearchViewController.m
//  ICrEAM
//
//  Created by Cty on 2016/11/07.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ICMAppointmentResearchViewController.h"
#import "AppointmentPlan.h"
#import "AppointmentToday.h"
#import "GetCarViewController.h"
#import "ICMAppointmentPreviewViewController.h"
#import "AppointmentViewController.h"
#import "ICMAppointmentTodayModel.h"
#import "ICMBasicInfoModel.h"
#import "ICMRepairMaintenanceModel.h"
#import "ICMActivityModel.h"
#import "ICMPartsTopModel.h"
#import "ICMPersonerModel.h"
#import "ICMRepairPartsModel.h"
#import "ICMAppointmentOtherInfoModel.h"
#import "ICMAppointmentPlanModel.h"
#import "CustomRecordModel.h"
@interface ICMAppointmentResearchViewController ()<UIScrollViewDelegate,ICMAppointmentPlanDelegate,ICMAppointmentTodayDelegate,UITextFieldDelegate>
@property (nonatomic,strong) UIButton *buttonToday;                               //今日预约按钮
@property (nonatomic,strong) UIButton *buttonPlan;                                //明日计划按钮
@property (nonatomic,strong) UIScrollView *container;
@property (nonatomic,strong) UIView *underLine;                                   //下划线
@property (nonatomic,strong) AppointmentToday *today;                             //今日页面
@property (nonatomic,strong) AppointmentPlan *plan;                               //计划页面
@property (nonatomic,assign) BOOL isToday;                                        //是否今日预约

//数据源
@property (nonatomic,strong) NSMutableArray *todayArray;
@property (nonatomic,strong) NSMutableArray *planArray;
@property (nonatomic, strong) ICMAppointmentBasicInfoModel *basicInfoModel;
@property (nonatomic, strong) ICMAppointmentOtherInfoModel *basicOtherModel;
@property (nonatomic, strong) ICMPersonerModel *personerModel;
@property (nonatomic, strong) ICMPartsTopModel *partsTopModel;
@property (nonatomic, strong) ICMActivityModel *activityModel;
@property (nonatomic, strong) ICMRepairMaintenancesModel *maintenancesModel;
@property (nonatomic, strong) ICMRepairPartsArrayModel *partsArrayModel;

@property (assign) NSInteger index;
@property (nonatomic,assign) BOOL isSearchByDate;
@end

@implementation ICMAppointmentResearchViewController

-(NSMutableArray *)todayArray{
    if (!_todayArray) {
        _todayArray = [NSMutableArray array];
    }
    return _todayArray;
}

-(NSMutableArray *)planArray{
    if (!_planArray) {
        _planArray = [NSMutableArray array];
    }
    return _planArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIView *topBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ActualHeight(40))];
    
    topBar.backgroundColor = Color(0xE5EBEB);
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //今日预约,预约计划
    [topBar addSubview: self.buttonToday];
    [topBar addSubview: self.buttonPlan];
    
    [self setCheckToToday];
    [self.view addSubview:topBar];
    
    //搜索框
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(ScreenWidth-ActualWidth(400), ActualHeight(4), ActualWidth(360), ActualHeight(32))];
    
    searchView.backgroundColor = [UIColor whiteColor];
    searchView.layer.cornerRadius = ActualHeight(32)/2.0;
    
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ActualWidth(4), ActualHeight(2), ActualWidth(28), ActualHeight(28))];
    
    searchImage.image = [UIImage imageNamed:GetCar_SearchIcon];
    
    [searchView addSubview:searchImage];
    
    UITextField * searchText = [[UITextField alloc]initWithFrame:CGRectMake(ActualWidth(32), 0, ActualWidth(360)-ActualWidth(32), ActualHeight(32))];
    searchText.placeholder = @"车牌号,预约人,预约人手机，服务顾问";
    searchText.delegate = self;
    searchText.font = [UIFont systemFontOfSize:14];
    searchText.returnKeyType = UIReturnKeySearch;
    [searchView addSubview:searchText];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:@"UITextFieldTextDidChangeNotification" object:searchText];
    
    [self.view addSubview:searchView];
    self.isToday = YES;
    self.isSearchByDate = NO;
 
    self.today = [AppointmentToday creatViewWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-ActualHeight(40)-NavBarAndStatusHeight) andModels:self.todayArray];
    self.today.delegate = self;
    self.today.tableViewToday.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getTodayWithString:@"" isToday:@"1101" start:@"" end:@""];
        
    }];
    
    [self.container addSubview:self.today];
    
    self.plan = [AppointmentPlan creatViewWithFrame:CGRectMake(ScreenWidth, 0, ScreenWidth, ScreenHeight-ActualHeight(40)-NavBarAndStatusHeight) andModels:nil];
    self.plan.delegate = self;
    [self.container addSubview:self.plan];
    
    
    [self.view addSubview:self.container];
    
    //下划线
    self.underLine = [[UIView alloc]initWithFrame:CGRectMake(ActualWidth(80), ActualHeight(39), ActualWidth(120), 1)];
    
    self.underLine.backgroundColor = TitleColor;
    
    [self.view addSubview:self.underLine];
    
    
    //注册通知 预约单转接车单成功后
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeAppointmentToGetCar:) name:@"DidChangeAppointmentToGetCar" object:nil];
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.isToday) {
        [self.today.tableViewToday.mj_header beginRefreshing];
    }
    
}

//默认支持大写
- (void)textFiledEditChanged:(NSNotification *)obj {
    UITextField *textField = obj.object;
    NSString *toBeString = textField.text;
    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            textField.text= toBeString.uppercaseString;
        }else{
            // 有高亮选择的字符串
        }
    }else {
        textField.text = textField.text.uppercaseString;
    }
}


//预约单转接车单成功后
- (void)didChangeAppointmentToGetCar:(NSNotification *)notification
{
    NSDictionary *dic = notification.userInfo;
    NSString *bookNoStr = dic[@"BOOKING_ORDER_NO"];
    for(ICMAppointmentTodayModel *model in self.todayArray)
    {
        if([model.BOOKING_ORDER_NO isEqualToString:bookNoStr])
        {
            [self.todayArray removeObject:model];
            break;
        }
    }
    for(ICMAppointmentTodayModel *model in self.planArray)
    {
        if([model.BOOKING_ORDER_NO isEqualToString:bookNoStr])
        {
            [self.planArray removeObject:model];
            break;
        }
    }
    [self.today reloadDataWithArray:self.todayArray];
    [self.plan reloadDataWithArray:self.planArray];
}


- (UIButton *)buttonToday{
    
    if(!_buttonToday){
        _buttonToday = [[UIButton alloc]initWithFrame:CGRectMake(ActualWidth(80), 0, ActualWidth(120), ActualHeight(40))];
        
        [_buttonToday setUpButtonWithNormolTitle:@"今日预约" selectedTitle:@"今日预约" normolTitleSize:NaviSize selectedTitleSize:NaviSize normolTitleColor:Color(0x020202) selectedTitleColor: TitleColor normolBcakImage:nil selectedBackImage:nil actionSEL:@selector(clickTodayButton:) target:self];
        
    }
    return _buttonToday;
    
}
- (UIButton *)buttonPlan{
    
    if(!_buttonPlan){
        
        _buttonPlan = [[UIButton alloc]initWithFrame:CGRectMake(self.buttonToday.rightEdge, 0, ActualWidth(120), ActualHeight(40))];
        
        [_buttonPlan setUpButtonWithNormolTitle:@"预约计划" selectedTitle:@"预约计划" normolTitleSize:NaviSize selectedTitleSize:NaviSize normolTitleColor:Color(0x020202) selectedTitleColor: TitleColor normolBcakImage:nil selectedBackImage:nil actionSEL:@selector(clickPlanButton:) target:self];
        
    }
    return _buttonPlan;
    
}

- (UIScrollView *)container{
    if(!_container){
        
        _container = [[UIScrollView alloc]initWithFrame:CGRectMake(0, ActualHeight(40), ScreenWidth, ScreenHeight-ActualHeight(40)-NavBarAndStatusHeight)];
        
        _container.contentSize = CGSizeMake(2*ScreenWidth, ScreenHeight-ActualHeight(40)-NavBarAndStatusHeight);
        _container.bounces = NO;
        _container.pagingEnabled = YES;
        _container.delegate = self;
        _container.showsHorizontalScrollIndicator = NO;
        _container.showsVerticalScrollIndicator = NO;
        
    }
    return _container;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    self.isSearchByDate = NO;
    if (self.isToday) {
        [self getTodayWithString:textField.text isToday:ICMEnumIntToString(ICMEnumAppointmentTypeToday) start:@"" end:@""];
    }else{
        [self getTodayWithString:textField.text isToday:ICMEnumIntToString(ICMEnumAppointmentTypePlan) start:@"" end:@""];
    }
    [textField resignFirstResponder];
    return YES;
}

- (void)clickTodayButton:(UIButton*)sender{
    if (self.index == 0) {
        return;
    }
    self.isToday = YES;
    self.isSearchByDate = NO;
    [self getTodayWithString:@"" isToday:ICMEnumIntToString(ICMEnumAppointmentTypeToday) start:@"" end:@""];
    self.index--;
    [self setCheckToToday];
    
}

- (void)clickPlanButton:(UIButton*)sender{
    if (self.index == 1) {
        return;
    }
    self.index++;
    self.isToday = NO;
    self.isSearchByDate = NO;
    [self getTodayWithString:@"" isToday:ICMEnumIntToString(ICMEnumAppointmentTypePlan) start:@"" end:@""];
    [self setCheckToPlan];
    
}

- (void)setCheckToToday{
    if(![self.buttonToday isSelected]){
        
        [self.buttonToday setSelected:YES];
        [self.buttonPlan setSelected:NO];
        
        [self.container scrollRectToVisible:CGRectMake(ScreenWidth*self.index, 0, ScreenWidth, ScreenHeight-ActualHeight(40)-NavBarAndStatusHeight) animated:YES];
        
    }
}

- (void)setCheckToPlan{
    if(![self.buttonPlan isSelected]){
        
        [self.buttonPlan setSelected:YES];
        [self.buttonToday setSelected:NO];
        [self.container scrollRectToVisible:CGRectMake(ScreenWidth*self.index, 0, ScreenWidth, ScreenHeight-ActualHeight(40)-NavBarAndStatusHeight) animated:YES];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //float offsetX = scrollView.contentOffset.x;
    self.index = roundf(scrollView.contentOffset.x/(ScreenWidth-ActualWidth(140)));
    
    if(self.index == 0){
        [self setCheckToToday];
    }else{
        [self setCheckToPlan];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    //    float offsetX = scrollView.contentOffset.x;
    self.index = roundf(scrollView.contentOffset.x/(ScreenWidth-ActualWidth(140)));
    
    if(self.index == 0){
        [self setCheckToToday];
    }else{
        [self setCheckToPlan];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGRect frame = self.underLine.frame;
    frame.origin.x = ActualWidth(80)+scrollView.contentOffset.x*ActualWidth(120)/ScreenWidth;
    self.underLine.frame = frame;
    
}

- (void)didClickPreViewWithIndex:(NSIndexPath *)index WithBookOrderNo:(NSString *)bookOrderNo
{
    [self didClickCellWithRECEPTION_NO:bookOrderNo type:@"3"];
}

- (void)didClickTodayPreViewWithIndex:(NSIndexPath *)index{
    ICMAppointmentTodayModel *model = self.todayArray[index.row];
    [self didClickCellWithRECEPTION_NO:model.BOOKING_ORDER_NO type:@"3"];
    
}

- (void)didClickTodaygetCarWithIndex:(NSIndexPath *)index{
    ICMAppointmentTodayModel *model = self.todayArray[index.row];
    [self didClickCellWithRECEPTION_NO:model.BOOKING_ORDER_NO type:@"2"];
    
}

- (void)didSearchByStartDate:(NSDate *)startDate andEndDate:(NSDate *)endDate{
    if (startDate && endDate) {
        self.isSearchByDate = YES;
        [self getTodayWithString:@"" isToday:ICMEnumIntToString(ICMEnumAppointmentTypePlan) start:[ICrEAMTool getStringWithDate:startDate] end:[ICrEAMTool getStringWithDate:endDate]];
    }
}

- (void)didClickTodayCellWithIndex:(NSIndexPath *)index{
    ICMAppointmentTodayModel *model = self.todayArray[index.row];
    if([model.CAN_EDIT isEqualToString:@"12781002"] && [ICrEAMTool isVW]){
        [self.view showString:@"微信的预约单，不允许编辑!" forSeconds:1.5];
        
        return;
    }

    [self didClickCellWithRECEPTION_NO:model.BOOKING_ORDER_NO type:@"0"];
}

- (void)didClickPlanCellWithIndex:(NSIndexPath *)index WithBookOrderNo:(NSString *)bookOrderNo
{
    
    [self didClickCellWithRECEPTION_NO:bookOrderNo type:@"1"];
    
}

- (void)getTodayWithString:(NSString *)text isToday:(NSString *)today start:(NSString *)start end:(NSString *)end {
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:text forKey:@"QUERY_CONDITION"];
    [parameters setObject:today forKey:@"QUERY_TYPE"]; //1101当天  1102 未来计划
    [parameters setObject:start forKey:@"QUERY_START_DATE"];
    [parameters setObject:end forKey:@"QUERY_END_DATE"];
    [parameters setObject:@1 forKey:@"CURRENT_PAGE"];
    [manager startGetRequestWithURL:QueryBookingOrder parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
         [self.today.tableViewToday.mj_header endRefreshing];
        if ([today isEqualToString:ICMEnumIntToString(ICMEnumAppointmentTypeToday)]) {
            if ([data[@"CODE"] integerValue] == 200) {
                [self.todayArray removeAllObjects];
                if (IsArr(data[@"TT_BOOKING_OEDER"])) {
                    NSArray *dataArray = data[@"TT_BOOKING_OEDER"];
                    
                    if (dataArray.count != 0 && dataArray) {
                        for (NSDictionary *searchData in dataArray) {
                            ICMAppointmentTodayModel * model = [ICMAppointmentTodayModel yy_modelWithDictionary:searchData];
                            [self.todayArray PACA_AddObject:model];
                        }
                    }
                }
                self.today.condition = text;
                [self.today reloadDataWithArray:self.todayArray];
            }
        }else{
            if ([data[@"CODE"] integerValue] == 200) {
                [self.planArray removeAllObjects];
                if (IsArr(data[@"TT_BOOKING_OEDER"])) {
                    NSArray *dataArray = data[@"TT_BOOKING_OEDER"];
                    
                    if (dataArray.count != 0 && dataArray) {
                        for (NSDictionary *searchData in dataArray) {
                            ICMAppointmentPlanModel * model = [ICMAppointmentPlanModel yy_modelWithDictionary:searchData];
                            [self.planArray PACA_AddObject:model];
                        }
                        
                    }
                }
                if (self.isSearchByDate) {
                    self.plan.condition = @"";
                } else {
                    self.plan.condition = text;
                }
                self.plan.isSearchByDate = self.isSearchByDate;
                [self.plan reloadDataWithArray:self.planArray];
            }
        }
    }];
}

#pragma mark 加载更多数据
- (void)loadMoreDataWithText:(NSString *)text WithType:(NSString *)type WithStartDate:(NSString *)startDate WithEndDate:(NSString *)endDate WithPage:(int)page
{
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:text forKey:@"QUERY_CONDITION"];
    [parameters setObject:type forKey:@"QUERY_TYPE"]; //1101当天  1102 未来计划
    [parameters setObject:startDate forKey:@"QUERY_START_DATE"];
    [parameters setObject:endDate forKey:@"QUERY_END_DATE"];
    [parameters setObject:@(page) forKey:@"CURRENT_PAGE"];
    [manager startGetRequestWithURL:QueryBookingOrder parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        [self.plan loadMoreDataWithData:data];
    }];
}



#pragma mark  type : 0今日 1计划 2接车 3预览
- (void)didClickCellWithRECEPTION_NO:(NSString *)RECEPTION_NO type:(NSString *)type{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:RECEPTION_NO forKey:@"ORDER_ID"];
    ICMRequestManager *manager = [[ICMRequestManager alloc]init];
    [manager startGetRequestWithURL:BookingOrderDetils parameters:parameters inHudView:self.view andResultBlock:^(id data, NSString *failText) {
        if ([data[@"CODE"] integerValue] == 200) {
            if (IsArr(data[@"TT_BOOKING_OEDER"])) {
                self.basicInfoModel = [ICMAppointmentBasicInfoModel yy_modelWithDictionary:data[@"TT_BOOKING_OEDER"][0]];
                self.basicOtherModel = [ICMAppointmentOtherInfoModel yy_modelWithDictionary:data[@"TT_BOOKING_OEDER"][0]];
                self.partsTopModel = [ICMPartsTopModel yy_modelWithDictionary:data[@"TT_BOOKING_OEDER"][0]];
                self.personerModel = [ICMPersonerModel yy_modelWithDictionary:data[@"TT_BOOKING_OEDER"][0]];
                
            }
            ICMBasicInfoModel *basicInfoModel = [ICMBasicInfoModel yy_modelWithDictionary:data[@"TT_BOOKING_OEDER"][0]];
            
            CustomRecordModel *recordModel = [[CustomRecordModel alloc]init];
            
            if(!IsArrEmpty(data[@"TM_CUSTOMER_RECORD"])){
            recordModel = [CustomRecordModel mj_objectWithKeyValues:data[@"TM_CUSTOMER_RECORD"][0]];
            
            }
            self.maintenancesModel = [ICMRepairMaintenancesModel yy_modelWithDictionary:data];
            [self.maintenancesModel createRepairMaintenanceBookingModel];
            
            self.partsArrayModel = [ICMRepairPartsArrayModel yy_modelWithDictionary:data];
            [self.partsArrayModel createRepairPartsBookingModel];
            
            self.activityModel = [ICMActivityModel yy_modelWithDictionary:data];
            [self.activityModel createActivityItemBookingModel];
            
            if ([type isEqualToString:@"2"]) {
                GetCarViewController *GCVC = [[GetCarViewController alloc]init];
                GCVC.isAppointmentType = YES;
                GCVC.basicInfoModel = basicInfoModel;
                //车辆性质
                GCVC.BUSINESS_KIND = basicInfoModel.BUSINESS_KIND;
                //备注清零
                GCVC.basicInfoModel.BUSINESS_DESC = @"";
                GCVC.customerModel = recordModel;
                GCVC.isGetCar = YES;
                GCVC.otherInfoModel = self.basicOtherModel;
                GCVC.otherInfoModel.REMARK = @"";
                GCVC.partsTopModel = self.partsTopModel;
                GCVC.repairEventModel = self.maintenancesModel;
                GCVC.repairEventModel.TT_RECPTION_LABOUR = self.maintenancesModel.TT_BOOKING_ORDER_LABOUR;
                GCVC.repairPartsModel = self.partsArrayModel;
                GCVC.repairPartsModel.TT_RECPTION_PART = self.partsArrayModel.TT_BOOKING_ORDER_PART;
                [self.navigationController pushViewController:GCVC animated:YES];
            }else if ([type isEqualToString:@"3"]){
                ICMAppointmentPreviewViewController *PVC = [[ICMAppointmentPreviewViewController alloc]init];
                PVC.basicInfoModel = self.basicInfoModel;
                PVC.basicOtherModel = self.basicOtherModel;
                PVC.partsTopModel = self.partsTopModel;
                PVC.maintenancesModel = self.maintenancesModel;
                PVC.partsArrayModel = self.partsArrayModel;
                PVC.activityModel = self.activityModel;
                [self.navigationController pushViewController:PVC animated:YES];
            }else{
                
                AppointmentViewController *appointmentViewController =[AppointmentViewController new];
                if(IsStrEmpty(_basicInfoModel.OWNER_NO)){
                    appointmentViewController.isRetainer = NO;
                }
                if(![ICrEAMTool isVW]){
                    appointmentViewController.basicInfoView.skEditType = YES;
                }else{
                    appointmentViewController.basicInfoView.skEditType = NO;
                }
                appointmentViewController.isEditType = YES;
                appointmentViewController.basicInfoModel = self.basicInfoModel;
                appointmentViewController.basicOtherModel = self.basicOtherModel;
                appointmentViewController.partsTopModel = self.partsTopModel;
                appointmentViewController.personerModel = self.personerModel;
                appointmentViewController.maintenancesModel = self.maintenancesModel;
                appointmentViewController.partsArrayModel = self.partsArrayModel;
                [self.navigationController pushViewController:appointmentViewController animated:YES];
            }
        }
    }];
}


@end
